package com.yupi.springbootinit.manager;

import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 专门提供限流基础服务
 */
@Service
public class RedisLimitManager {
    @Resource
    private RedissonClient redissonClient;
    public void doRateLimit(String key){
        //创建一个限流器
        RRateLimiter limiter = redissonClient.getRateLimiter(key);
        //设置1秒2次
        limiter.trySetRate(RateType.OVERALL,2,1, RateIntervalUnit.SECONDS);
        boolean canOp = limiter.tryAcquire(1);
        if (!canOp){
            throw new BusinessException(ErrorCode.TO_MANY_REQUEST);
        }
    }
}
